package concurrent.semaphore;

import org.junit.Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量
 *
 * @author LoneRanger
 */
public class SemaphoreTest {

	/**
	 * 停车场同时容纳的车辆10
	 */
	private static Semaphore semaphore = new Semaphore(2);

	@Test
	public void test() throws InterruptedException {
		for (int i = 0; i < 20; i++) {
			new Thread(() -> {
				System.out.println(Thread.currentThread().getName() + "准备来停车");
				if (semaphore.availablePermits() == 0) {
					System.out.println(Thread.currentThread().getName() + "车位不足，请耐心等待");
				}
				try {
					//获取令牌尝试进入停车场
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() + "获取到了车位");
					TimeUnit.SECONDS.sleep(3);
					System.out.println(Thread.currentThread().getName() + "驶出停车场");
					//释放令牌，腾出停车场车位
					semaphore.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}, "车主" + i).start();
		}
		TimeUnit.SECONDS.sleep(40);
	}

}
